package com.amz.analyzer.google.trans;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class GTransApi {

    public static String translateSingle(String text) {
        String url = "http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=en_US&tl=zh_CN";
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("q", text);

        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化

        //服务端返回的json格式："
        String result = client.postForObject(url, requestEntity, String.class);

//        ResponseEntity<ResultVO> response = client.exchange(url, method, requestEntity, ResultVO.class);
//        ResultVO body = response.getBody();
//        return (String) body.getData();
//        System.out.println(result);
        return result;
    }
}
